package com.jprocms.module.cms.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

@Slf4j
public class WordReader {

    public static String getDocxText(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            XWPFDocument document = new XWPFDocument(fis);
            // 读取所有段落
            StringBuilder stringBuilder = new StringBuilder();
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            try {
                for (XWPFParagraph xwpfParagraph : paragraphs) {
                    // 获取当前段落的所有run
                    List<XWPFRun> runs = xwpfParagraph.getRuns();
                    for (XWPFRun run : runs) {
                        final String text = run.getText(run.getCharacterSpacing());
                        stringBuilder.append(text);
                    }
                }
                log.debug("getWordText 读取word {}", stringBuilder.toString());
            } catch (Exception e) {
                log.error("getWordText 读取word失败,{}", e.getMessage());
            } finally {
                fis.close();
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            log.error("getWordText 读取word失败,{}", e.getMessage());
        }
        return null;
    }

    public static String getDocText(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            // 将MultipartFile转换为HWPFDocument
            HWPFDocument doc = new HWPFDocument(fis);
            String text = doc.getDocumentText();
            fis.close();
            return text;
        } catch (Exception e) {
            log.error("getWordText 读取word失败,{}", e.getMessage());
        }
        return null;
    }

}
